<template>
  <div class="return-view">
    <!-- 顶部导航栏 -->
    <van-nav-bar
        title="退回"
        left-arrow
        @click-left="onClickLeft"
        fixed
    />
    <div class="return-form">
      <div class="form-item">
        <div class="form-label">
          <span class="required">*</span>
          <span class="label-text">退回原因</span>
        </div>
        <van-field
            v-model="formData.processreasonone"
            name="processreasonone"
            type="textarea"
            rows="4"
            placeholder="请输入退回原因"
            required
        />
      </div>
    </div>

    <van-field
        name="uploader"
        label="附件"
    >
      <template #label>
        <span class="required">*</span>
        <span class="label-text">附件</span>
      </template>
      <template #input>
        <van-uploader
            v-model="fileList"
            :max-count="3"
            :before-read="beforeRead"
            :after-read="afterRead"
            multiple
        />
      </template>
    </van-field>
    <!-- 确定按钮 -->
    <div class="submit-btn">
      <van-button type="primary" block @click="handleSubmit">确定</van-button>
    </div>
  </div>
</template>

<script>
import { NavBar, Field, Uploader, Button, Toast } from 'vant';

export default {
  name: 'ReturnView',
  components: {
    [NavBar.name]: NavBar,
    [Field.name]: Field,
    [Uploader.name]: Uploader,
    [Button.name]: Button,
  },
  data() {
    return {
      formData: {
        shippingapplication: {
          ticketId: null,
          shippingstatus: 3
        },
        process: {
          processreasonone: '',
          processannexone: '',
          processstatus:''
        }
      },
      updateData: {
        id: null,
        shippingstatus: 3
      },
      fileList: []
    }
  },
  methods: {
    onClickLeft() {
      this.$router.back()
    },
    handleSubmit() {
      if (this.fileList.some(file => file.status === 'uploading')) {
        Toast('请等待文件上传完成');
        return;
      }

      // 先执行 update
      this.axios.post('http://localhost:9999/api-central-service/shipping/update', this.updateData)
          .then(res => {
            if (res.data.code === 1) {
              // update 成功后执行 add
              this.axios.post('http://localhost:9999/api-central-service/shipping/return', this.formData)
                  .then(res => {
                    if (res.data.code === 1) {
                      Toast.success('退回成功');
                      setTimeout(() => {
                        this.$router.push('/ticket');
                      }, 1500);
                    } else {
                      Toast.fail(res.data.message || '退回失败');
                    }
                  });
            } else {
              Toast.fail(res.data.message || '状态更新失败');
            }
          });
    },
    // 上传前的校验
    beforeRead(file) {
      // 限制文件大小（这里限制为 10MB）
      const maxSize = 10 * 1024 * 1024;
      if (file.size > maxSize) {
        Toast('文件大小不能超过 10MB');
        return false;
      }
      return true;
    },
    // 上传后的处理
    afterRead(file) {
      // 如果是多文件上传，file 是一个数组
      const files = Array.isArray(file) ? file : [file];
      files.forEach((item) => {
        // 创建 FormData
        const formData = new FormData();
        formData.append('file', item.file);

        // 上传文件到服务器
        this.axios.post('http://localhost:9999/api-central-service/oss/upload', formData, {
          headers: {
            // 设置请求头
            'Content-Type': 'multipart/form-data',
          },
        })
            .then(res => {
              if (res.data) {
                // 初始化 shippingannex 为字符串
                if (!this.formData.processannexone) {
                  this.formData.processannexone = '';
                }
                // 将文件 URL 添加到字符串中，用逗号分隔
                this.formData.processannexone = this.formData.processannexone
                    ? this.formData.processannexone + ',' + res.data
                    : res.data;
                Toast.success('文件上传成功');
              } else {
                Toast.fail('文件上传失败');
                const index = this.fileList.indexOf(item);
                if (index !== -1) {
                  this.fileList.splice(index, 1);
                }
              }
            })
      })
    }
  },
  mounted() {
    // 从路由参数获取 id
    this.updateData.id = this.$route.query.id;
    this.formData.shippingapplication.ticketId = this.$route.query.id;
    this.formData.processstatus=this.$route.query.id;
  }
}
</script>

<style scoped>
.return-view {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-top: 46px;
}

.return-form {
  padding: 16px;
}

.form-item {
  background: #fff;
  padding: 16px;
  margin-bottom: 12px;
  border-radius: 8px;
}

.form-label {
  margin-bottom: 8px;
  font-size: 14px;
  color: #323233;
}

.required {
  color: #ee0a24;
  margin-right: 4px;
}

.upload-hint {
  margin-top: 8px;
  font-size: 12px;
  color: #969799;
}

.submit-btn {
  margin-top: 24px;
  padding: 0 16px;
}

:deep(.van-field__control) {
  min-height: 100px;
}
</style>